home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / text / faqs / perl-faq.part4 < prev    next >
Encoding:
Internet Message Format  |  1993-10-03  |  11.7 KB

  1. Subject: Perl Frequently Asked Questions, part 4 of 4
  2. Newsgroups: comp.lang.perl,news.answers
  3. From: Tom Christiansen <tchrist@cs.Colorado.EDU>
  4. Date: Sat, 2 Oct 1993 06:38:13 GMT
  5.  
  6. Archive-name: perl-faq/part4
  7. Version: $Id: perl-tech2,v 1.1 93/10/02 00:27:03 tchrist Exp Locker: tchrist $
  8.  
  9. This posting contains answers to the following technical questions
  10. regarding Perl:
  11.  
  12. 2.29) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  13. 2.30) Do I always/never have to quote my strings or use semicolons?
  14. 2.31) How can I translate tildes in a filename?
  15. 2.32) How can I convert my shell script to Perl?
  16. 2.33) What is variable suicide and how can I prevent it?
  17. 2.34) Can I use Perl regular expressions to match balanced text?
  18. 2.35) Can I use Perl to run a telnet or ftp session?
  19. 2.36) What does "Malformed command links" mean?
  20. 2.37) How can I set up a footer format to be used with write()?
  21. 2.38) Why does my Perl program keep growing in size?
  22. 2.39) Can I do RPC in Perl?
  23. 2.40) What's the difference between delete and undef with %tables?
  24. 2.41) How do I do a "tail -f" in Perl?
  25.  
  26.  
  27. 2.29) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  28.  
  29.     Because some stdio's set error and eof flags that need clearing.
  30.  
  31.     Try keeping around the seekpointer and go there, like this:
  32.      $where = tell(LOG);
  33.      seek(LOG, $where, 0);
  34.  
  35.     If that doesn't work, try seeking to a different part of the file and
  36.     then back.  If that doesn't work, try seeking to a different part of
  37.     the file, reading something, and then seeking back.  If that doesn't
  38.     work, give up on your stdio package and use sysread.  You can't call
  39.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  40.     handler, you're out of luck.  Best to just use sysread() from the
  41.     start for the tty.
  42.  
  43.  
  44. 2.30) Do I always/never have to quote my strings or use semicolons?
  45.  
  46.     You don't have to quote strings that can't mean anything else
  47.     in the language, like identifiers with any upper-case letters
  48.     in them.  Therefore, it's fine to do this:
  49.  
  50.     $SIG{INT} = Timeout_Routine;
  51.     or 
  52.  
  53.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  54.  
  55.     but you can't get away with this:
  56.  
  57.     $foo{while} = until;
  58.  
  59.     in place of 
  60.  
  61.     $foo{'while'} = 'until';
  62.  
  63.     The requirements on semicolons have been increasingly relaxed.  You no
  64.     longer need one at the end of a block, but stylistically, you're
  65.     better to use them if you don't put the curly brace on the same line:
  66.  
  67.     for (1..10) { print }
  68.  
  69.     is ok, as is
  70.  
  71.     @nlist = sort { $a <=> $b } @olist;
  72.  
  73.     but you probably shouldn't do this:
  74.     
  75.     for ($i = 0; $i < @a; $i++) {
  76.         print "i is $i\n"  # <-- oops!
  77.     } 
  78.  
  79.     because you might want to add lines later, and anyway, 
  80.     it looks funny. :-)
  81.  
  82.  
  83. 2.31) How can I translate tildes in a filename?
  84.  
  85.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  86.     The classic request is to be able to do something like:
  87.  
  88.     open(FILE, "~/dir1/file1");
  89.     open(FILE, "~tchrist/dir1/file1");
  90.  
  91.     which doesn't work.  (And you don't know it, because you 
  92.     did a system call without an "|| die" clause! :-)
  93.  
  94.     If you *know* you're on a system with the csh, and you *know*
  95.     that Larry hasn't internalized file globbing, then you could
  96.     get away with 
  97.  
  98.     $filename = <~tchrist/dir1/file1>;
  99.  
  100.     but that's pretty iffy.
  101.  
  102.     A better way is to do the translation yourself, as in:
  103.  
  104.     $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  105.  
  106.     More robust and efficient versions that checked for error conditions,
  107.     handed simple ~/blah notation, and cached lookups are all reasonable
  108.     enhancements.
  109.  
  110.  
  111. 2.32) How can I convert my shell script to Perl?
  112.  
  113.     Larry's standard answer for this is to send your script to me (Tom
  114.     Christiansen) with appropriate supplications and offerings.  :-(
  115.     That's because there's no automatic machine translator.  Even if you
  116.     were, you wouldn't gain a lot, as most of the external programs would
  117.     still get called.  It's the same problem as blind translation into C:
  118.     you're still apt to be bogged down by exec()s.  You have to analyze
  119.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  120.     not uncommon to see one, two, or even three orders of magnitude of
  121.     speed difference between the brute-force and the recoded approaches.
  122.  
  123.  
  124. 2.33) What is variable suicide and how can I prevent it?
  125.  
  126.     Variable suicide is a nasty sideeffect of dynamic scoping and
  127.     the way variables are passed by reference.  If you say
  128.  
  129.     $x = 17;
  130.     &munge($x);
  131.     sub munge {
  132.         local($x);
  133.         local($myvar) = $_[0];
  134.         ...
  135.     } 
  136.  
  137.     Then you have just clubbered $_[0]!  Why this is occurring 
  138.     is pretty heavy wizardry: the reference to $x stored in 
  139.     $_[0] was temporarily occluded by the previous local($x)
  140.     statement (which, you're recall, occurs at run-time, not
  141.     compile-time).  The work around is simple, however: declare
  142.     your formal parameters first:
  143.  
  144.     sub munge {
  145.         local($myvar) = $_[0];
  146.         local($x);
  147.         ...
  148.     }
  149.  
  150.     That doesn't help you if you're going to be trying to access
  151.     @_ directly after the local()s.  In this case, careful use
  152.     of the package facility is your only recourse.
  153.  
  154.     Another manifestation of this problem occurs due to the
  155.     magical nature of the index variable in a foreach() loop.
  156.  
  157.     @num = 0 .. 4;
  158.     print "num begin  @num\n";
  159.     foreach $m (@num) { &ug }
  160.     print "num finish @num\n";
  161.     sub ug {
  162.         local($m) = 42;
  163.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  164.     }
  165.     
  166.     Which prints out the mysterious:
  167.  
  168.     num begin  0 1 2 3 4
  169.     m=42  42,1,2,3
  170.     m=42  0,42,2,3
  171.     m=42  0,1,42,3
  172.     m=42  0,1,2,42
  173.     m=42  0,1,2,3
  174.     num finish 0 1 2 3 4
  175.  
  176.     What's happening here is that $m is an alias for each 
  177.     element of @num.  Inside &ug, you temporarily change
  178.     $m.  Well, that means that you've also temporarily 
  179.     changed whatever $m is an alias to!!  The only workaround
  180.     is to be careful with global variables, using packages,
  181.     and/or just be aware of this potential in foreach() loops.
  182.  
  183.     The perl5 static autos via "my" will not have this problem.
  184.  
  185.  
  186. 2.34) Can I use Perl regular expressions to match balanced text?
  187.  
  188.     No, or at least, not by the themselves.
  189.  
  190.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  191.     strictly regular because they do backtracking (the \1 notation), you
  192.     still can't do it.  You need to employ auxiliary logic.  A simple
  193.     approach would involve keeping a bit of state around, something 
  194.     vaguely like this (although we don't handle patterns on the same line):
  195.  
  196.     while(<>) {
  197.         if (/pat1/) {
  198.         if ($inpat++ > 0) { warn "already saw pat1" } 
  199.         redo;
  200.         } 
  201.         if (/pat2/) {
  202.         if (--$inpat < 0) { warn "never saw pat1" } 
  203.         redo;
  204.         } 
  205.     }
  206.  
  207.     A rather more elaborate subroutine to pull out balanced and possibly
  208.     nested single chars, like ` and ', { and }, or ( and ) can be found
  209.     on convex.com in /pub/perl/scripts/pull_quotes.
  210.  
  211.  
  212. 2.35) Can I use Perl to run a telnet or ftp session?
  213.  
  214.     Sure, you can connect directly to them using sockets, or you can run a
  215.     session on a pty.  In either case, Randal's chat2 package, which is
  216.     distributed with the perl source, will come in handly.  It address
  217.     much the same problem space as Don Libes's expect package does.  Two
  218.     examples of using managing an ftp session using chat2 can be found on
  219.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  220.  
  221.     Caveat lector: chat2 is documented only by example, may not run on
  222.     System V systems, and is subtly machine dependent both in its ideas
  223.     of networking and in pseudottys.
  224.  
  225.  
  226. 2.36) What does "Malformed command links" mean?
  227.  
  228.     This is a bug in 4.035.  While in general it's merely a cosmetic
  229.     problem, it often comanifests with a highly undesirable coredumping
  230.     problem.  Programs known to be affected by the fatal coredump include
  231.     plum and pcops.  Since perl5 is pretty much a total rewrite, we can
  232.     count on it being fixed then, but if anyone tracks down the coredump
  233.     problem before then, a significant portion of the Perl world would
  234.     rejoice.
  235.  
  236.  
  237. 2.37) How can I set up a footer format to be used with write()?
  238.  
  239.     While the $^ variable contains the name of the current header format,
  240.     there is no corresponding mechanism to automatically do the same thing
  241.     for a footer.  Not knowing how big a format is going to be until you
  242.     evaluate it is one of the major problems.
  243.  
  244.     If you have a fixed-size footer, you can get footers by checking for
  245.     line left on page ($-) before each write, and printing the footer
  246.     yourself if necessary.
  247.  
  248.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  249.     and always write()ing to the KID, who then postprocesses its STDIN to
  250.     rearrange headers and footers however you like.  Not very convenient,
  251.     but doable.
  252.  
  253.  
  254. 2.38) Why does my Perl program keep growing in size?
  255.  
  256.     While there may be a real memory leak in the Perl source code or even
  257.     whichever malloc() you're using, common causes are incomplete eval()s
  258.     or local()s in loops.
  259.  
  260.     An eval() which terminates in error due to a failed parsing 
  261.     will leave a bit of memory unusable.
  262.  
  263.     A local() inside a loop:
  264.  
  265.     for (1..100) {
  266.         local(@array);
  267.     } 
  268.  
  269.     will build up 100 versions of @array before the loop is done.
  270.     The work-around is:
  271.  
  272.     local(@array);
  273.     for (1..100) {
  274.         undef @array;
  275.     } 
  276.  
  277.     Larry reports that this behavior is fixed for perl5.
  278.  
  279.  
  280. 2.39) Can I do RPC in Perl?
  281.  
  282.     Yes, you can, since Perl has access to sockets.  An example of the rup
  283.     program written in Perl can be found in the script ruptime.pl at
  284.     the scripts archive on coombs.anu.edu.au .   I warn you, however,
  285.     that it's not a pretty site, as it's used nothing from h2ph or c2ph, 
  286.     so everything is utterly hard-wired.
  287.  
  288.  
  289. 2.40) What's the difference between delete and undef with %tables?
  290.  
  291.     Pictures help...  here's the %ary table:
  292.  
  293.           keys  values
  294.         +------+------+
  295.         |  a   |  3   |
  296.         |  x   |  7   |
  297.         |  d   |  0   |
  298.         |  e   |  2   |
  299.         +------+------+
  300.  
  301.     And these conditions hold
  302.  
  303.         $ary{'a'}                       is true
  304.         $ary{'d'}                       is false
  305.         defined $ary{'d'}               is true
  306.         defined $ary{'a'}               is true
  307.         grep ($_ eq 'a', keys %ary)     is true
  308.  
  309.     If you now say 
  310.  
  311.         undef $ary{'a'}
  312.  
  313.     your table now reads:
  314.         
  315.  
  316.           keys  values
  317.         +------+------+
  318.         |  a   | undef|
  319.         |  x   |  7   |
  320.         |  d   |  0   |
  321.         |  e   |  2   |
  322.         +------+------+
  323.  
  324.     and these conditions now hold; changes in caps:
  325.  
  326.         $ary{'a'}                       is FALSE
  327.         $ary{'d'}                       is false
  328.         defined $ary{'d'}               is true
  329.         defined $ary{'a'}               is FALSE
  330.         grep ($_ eq 'a', keys %ary)     is true
  331.  
  332.     Notise the last two: you have an undef value, but a defined key!
  333.  
  334.     Now, consider this:
  335.  
  336.         delete $ary{'a'}
  337.  
  338.     your table now reads:
  339.  
  340.           keys  values
  341.         +------+------+
  342.         |  x   |  7   |
  343.         |  d   |  0   |
  344.         |  e   |  2   |
  345.         +------+------+
  346.  
  347.     and these conditions now hold; changes in caps:
  348.  
  349.         $ary{'a'}                       is false
  350.         $ary{'d'}                       is false
  351.         defined $ary{'d'}               is true
  352.         defined $ary{'a'}               is false
  353.         grep ($_ eq 'a', keys %ary)     is FALSE
  354.  
  355.     See, the whole entry is gone!
  356.  
  357. 2.41) How do I do a "tail -f" in Perl?
  358.  
  359.     Larry says that the solution is to put a call to seek in yourself. 
  360.     First try
  361.  
  362.         seek(GWFILE, 0, 1);
  363.  
  364.     If that doesn't work (depends on your stdio implementation), then
  365.     you need something more like this:
  366.  
  367.  
  368.     for(;;) {
  369.         for ($curpos = tell(GWFILE); $_ = <GWFILE>; $curpos = tell(GWFILE)) {
  370.            search for some stuff and put it into files
  371.         }
  372.         sleep for a while 
  373.         seek(GWFILE, $curpos, 0);
  374.     }
  375. -- 
  376.     Tom Christiansen      tchrist@cs.colorado.edu       
  377.             Consultant
  378.     Boulder Colorado  303-444-3212
  379.  
  380.